package net.bac.sbe.web.sonar.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.HorizontalAlignment;

import net.bac.sbe.web.sonar.client.view.ApplicationView;
import net.bac.sbe.web.sonar.client.view.ModuleView;
import net.bac.sbe.web.sonar.client.view.ReportView;
import net.bac.sbe.web.sonar.client.view.RepositoryView;
import net.bac.sbe.web.sonar.client.widgets.SbeListBox;
import net.bac.sbe.web.sonar.client.widgets.TextBoxWithPlaceholder;
import net.bac.sbe.web.sonar.shared.FieldVerifier;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ApplicationManager implements EntryPoint {
	private static final String SONAR_REPORT_ID = "sonarReport";

	private static final String ITEM_TO_RETAIN_REPORT_ID = "itemToRetainReport";

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";


	private final ApplicationMaintenanceServiceAsync appMaintenanceServiceAsync = GWT
			.create(ApplicationMaintenanceService.class);

	final DialogBox waitDialogBox = new DialogBox();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		
		
		waitDialogBox.setText("Procesando...");
		waitDialogBox.setAnimationEnabled(true);
		final VerticalPanel processDialogPanel = new VerticalPanel();
		processDialogPanel.addStyleName("dialogVPanel");
		processDialogPanel
		.add(new HTML(
				"<br><b>Por favor espere ...</b>"));
		Image image = new Image("images/loading.gif");
		processDialogPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		processDialogPanel.add(image);
		waitDialogBox.add(processDialogPanel);
		
		
		
		final Button addAppButton = new Button("Agregar aplicacion");
		final Button deleteAppButton = new Button("Eliminar aplicacion");

		final Button deleteSelectedAppsButton = new Button("Eliminar seleccionadas");
		final Button closeDeleteBoxButton = new Button("Cerrar");

		// applications
		final Label errorLabel = new Label();

		final Label deleteApplicationLabel = new Label("Seleccione las aplicaciones a eliminar:");

		// We can add style names to widgets
		addAppButton.addStyleName("sendButton");


		VerticalPanel verticalButtonPanel = new VerticalPanel();
		HorizontalPanel deleteButtonsPanel = new HorizontalPanel();
		verticalButtonPanel.add(addAppButton);
		verticalButtonPanel.add(deleteAppButton);


		final SbeListBox multiBox = new SbeListBox(true);




		final DialogBox deleteApplicationDialogBox = new DialogBox();
		deleteApplicationDialogBox.setText("Borrar aplicacion: ");
		deleteApplicationDialogBox.setAnimationEnabled(true);

		final VerticalPanel deleteApplicationsDialogPanel = new VerticalPanel();
		deleteApplicationsDialogPanel.add(deleteApplicationLabel);
		deleteApplicationsDialogPanel.add(multiBox);

		deleteButtonsPanel.add(deleteSelectedAppsButton);
		deleteButtonsPanel.add(closeDeleteBoxButton);

		deleteApplicationsDialogPanel.add(deleteButtonsPanel);

		deleteApplicationDialogBox.add(deleteApplicationsDialogPanel);





		deleteAppButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				invokeAsynchronousApplicationsQuery(multiBox);
				deleteApplicationDialogBox.center();
				deleteApplicationDialogBox.show();
			}
		});

		deleteSelectedAppsButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				deleteApplicationDialogBox.hide();
				
				
				
				System.out.println("SE MOSTRO EL DIALOGO DE PROCESO DE ESPERA");
				
				final int size = multiBox.getSelectedItems().size();
				
				ArrayList<String> temporal = new ArrayList<String>();
				
				for (String repositoriesToDelete : multiBox.getSelectedItems()){
					temporal.add(repositoriesToDelete);
				}
				
				for (String repositoriesToDelete : temporal) {
					
					waitDialogBox.center();
					waitDialogBox.show();
					
					final String repositoryName = repositoriesToDelete;
					appMaintenanceServiceAsync.deleteApplication(repositoriesToDelete,
							new AsyncCallback<Boolean>() {

								@Override
								public void onFailure(Throwable caught) {
									waitDialogBox.hide();
									Window.alert("Error al borrar las aplicaciones seleccionadas, valide el Log de la aplicación");
								}

								@Override
								public void onSuccess(Boolean result) {
									
									if(result){
										Window.alert("Se elimino el repositorio: " + repositoryName);
											
										multiBox.clear();
										invokeAsynchronousApplicationsQuery(multiBox);
										
									}
									else{
										Window.alert("Error al borrar las aplicaciones seleccionadas, valide el Log de la aplicación");
									}
									
									waitDialogBox.hide();
								}
							});
				}

				
			}
		});

		closeDeleteBoxButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				deleteApplicationDialogBox.hide();
				multiBox.clear();
			}
		});


		RootPanel.get("buttonContainer").add(verticalButtonPanel);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		setAplicationInsertionInterface(addAppButton);
	}

	private void invokeAsynchronousApplicationsQuery(final SbeListBox multiBox) {

		appMaintenanceServiceAsync.getApplications(
				new AsyncCallback<List<String>>() {
					public void onFailure(Throwable caught) {
						//do nothing
					}

					public void onSuccess(List<String> result) {
						for (String app : result) {
							multiBox.addItem(app, app);
						}
						multiBox.setWidth("28em");
						multiBox.setVisibleItemCount(20);
					}
				});
	}


	

	/**
	 * Método que prepara la interface para la inclusión de una nueva aplicación
	 * @param addAppButton
	 */
	private void setAplicationInsertionInterface(final Button addAppButton) {
		final DialogBox processDialogBox = new DialogBox();
		processDialogBox.setText("Incluir aplicacion: ");
		processDialogBox.setAnimationEnabled(true);
		final VerticalPanel processDialogPanel = new VerticalPanel();
		final VerticalPanel applicationsPanel = new VerticalPanel();

		applicationsPanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		processDialogPanel.addStyleName("dialogVPanel");
		processDialogPanel
		.add(new HTML(
				"<br><b>Complete los datos de las aplicaciones a incluir</b>"));


		final TextBoxWithPlaceholder repositoryName = new TextBoxWithPlaceholder();
		final TextBoxWithPlaceholder repositoryURL = new TextBoxWithPlaceholder();

		final List<List<TextBoxWithPlaceholder>> applications = new ArrayList<List<TextBoxWithPlaceholder>>(2);
		final Map<String, List<ModuleView>> modules = new HashMap<String, List<ModuleView>>(2);


		repositoryName.setPlaceholder("Nombre del repositorio");
		repositoryName.setWidth("300px");
		repositoryURL.setPlaceholder("URL del repositorio");
		repositoryURL.setWidth("300px");





		processDialogPanel.add(repositoryName);
		processDialogPanel.add(repositoryURL);

		processDialogPanel.add(applicationsPanel);


		Button addApplicationButton = new Button("Agregar Aplicacion");

		addApplicationButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				TextBoxWithPlaceholder applicationName = new TextBoxWithPlaceholder();
				applicationName.setPlaceholder("Nombre: ");
				applicationName.setWidth("300px");
				TextBoxWithPlaceholder applicationRegularExpression = new TextBoxWithPlaceholder();
				applicationRegularExpression.setPlaceholder("Expresion regular: ");
				TextBoxWithPlaceholder applicationSonarKey = new TextBoxWithPlaceholder();
				applicationSonarKey.setPlaceholder("Llave de Sonar: ");
				applicationSonarKey.setWidth("300px");
				
				applicationRegularExpression.setWidth("300px");
				final Label applicationQuantity = new Label("Cantidad de modulos: 0");
				Button addModuleButton = new Button("Agregar Modulo");



				addModuleButton.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
					    final DialogBox moduleDialogBox = new DialogBox();
					    Button closeButton = new Button("Cerrar");
					    Button addButton = new Button("Agregar Modulo");
					    final TextBoxWithPlaceholder name = new TextBoxWithPlaceholder();
					    name.setPlaceholder("Nombre");
					    name.setWidth("300px");

					    final TextBoxWithPlaceholder regularExpression = new TextBoxWithPlaceholder();
					    regularExpression.setPlaceholder("Expresion regular");
					    regularExpression.setWidth("300px");

					    final TextBoxWithPlaceholder artifactId = new TextBoxWithPlaceholder();
					    artifactId.setPlaceholder("Id de artefacto");
					    artifactId.setWidth("300px");

					    final TextBoxWithPlaceholder sonarKey = new TextBoxWithPlaceholder();
					    sonarKey.setPlaceholder("Llave de sonar");
					    sonarKey.setWidth("300px");

					    final TextBoxWithPlaceholder sourcePath = new TextBoxWithPlaceholder();
					    sourcePath.setPlaceholder("Ruta de Fuentes Java");
					    sourcePath.setWidth("300px");
					    
					    
					    moduleDialogBox.setText("Agregar Modulo a la aplicacion: ");
					    moduleDialogBox.setAnimationEnabled(true);

					    VerticalPanel verticalModules = new VerticalPanel();
					    HorizontalPanel horizontalModules = new HorizontalPanel();

					    verticalModules.add(name);
					    verticalModules.add(regularExpression);
					    verticalModules.add(artifactId);
					    verticalModules.add(sonarKey);
					    verticalModules.add(sourcePath);

					    horizontalModules.add(addButton);
					    horizontalModules.add(closeButton);
					    verticalModules.add(horizontalModules);

					    moduleDialogBox.add(verticalModules);



						closeButton.addClickHandler(new ClickHandler() {
							public void onClick(ClickEvent event) {
								moduleDialogBox.hide();
							}
						});

						addButton.addClickHandler(new ClickHandler() {
							public void onClick(ClickEvent event) {
								ModuleView view = new ModuleView();
								view.setName(name.getText());
								view.setArtifactId(artifactId.getText());
								view.setRegularExpression(regularExpression.getText());
								view.setSonarKey(sonarKey.getText());
//
								modules.get(String.valueOf(applications.size())).add(view);

								applicationQuantity.setText("Cantidad de modulos: " + modules.get(String.valueOf(applications.size())).size());

								moduleDialogBox.hide();
							}
						});

						moduleDialogBox.center();
						moduleDialogBox.show();


					}
				});


				List<TextBoxWithPlaceholder> applicationFields = new ArrayList<TextBoxWithPlaceholder>(2);
				applicationFields.add(applicationName);
				applicationFields.add(applicationRegularExpression);
				applicationFields.add(applicationSonarKey);
				applications.add(applicationFields);

				applicationsPanel.add(new HTML(
						"<br><b>Aplicacion " + applications.size() + ": </b>"));
				modules.put(String.valueOf(applications.size()), new ArrayList<ModuleView>());

				applicationsPanel.add(applicationName);
				applicationsPanel.add(applicationRegularExpression);
				applicationsPanel.add(applicationSonarKey);
				applicationsPanel.add(applicationQuantity);
				applicationsPanel.add(addModuleButton);
			}
		});

		final Button saveRepository = new Button("Guardar");

		saveRepository.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				waitDialogBox.center();
				waitDialogBox.show();
				
				
				final RepositoryView view = new RepositoryView();
				view.setRepositoryName(repositoryName.getText());
				view.setSvnURL(repositoryURL.getText());

				int counter = 0;

				for (List<TextBoxWithPlaceholder> textBoxWithPlaceholder : applications) {
					counter++;
					ApplicationView appView = new ApplicationView();
					appView.setModules(modules.get(String.valueOf(counter)));
					appView.setName(textBoxWithPlaceholder.get(0).getText());
					appView.setRegularExpression(textBoxWithPlaceholder.get(1).getText());
					appView.setSonarKey(textBoxWithPlaceholder.get(2).getText());

					view.addApplication(appView);
				}

				System.out.println(view);

				appMaintenanceServiceAsync.insertApplication(view, new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
						System.out.println("Error al invocar el servicio");
						waitDialogBox.hide();
						Window.alert("Ocurrio un error al insertar la aplicacion, verifique los logs de la aplicacion");
					}

					@Override
					public void onSuccess(Boolean result) {
						System.out.println("Invocacion finalizada exitosamente");
						
						waitDialogBox.hide();
						
						resetInterface(addAppButton, processDialogBox, applicationsPanel,
								repositoryName, repositoryURL, applications, modules);
						
						Window.alert("Se incluyo el repositorio: " + view.getRepositoryName());
					}
				});

//				resetInterface(addAppButton, processDialogBox, applicationsPanel,
//						repositoryName, repositoryURL, applications, modules);

			}
		});





		HorizontalPanel buttonPanel = new HorizontalPanel();
		buttonPanel.addStyleName("dialogVPanel");

		processDialogPanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		System.out.println("Si cambio la clase");

		buttonPanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		Button closeAddApplicationButton = new Button("Cerrar");

		closeAddApplicationButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				resetInterface(addAppButton, processDialogBox, applicationsPanel,
						repositoryName, repositoryURL, applications, modules);
			}
		});

		buttonPanel.add(addApplicationButton);
		buttonPanel.add(saveRepository);
		buttonPanel.add(closeAddApplicationButton);


		processDialogPanel.add(buttonPanel);

		processDialogBox.add(processDialogPanel);

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Reportes Generados");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();

		final VerticalPanel dialogVPanel = new VerticalPanel();



		final VerticalPanel linksDialogPanel = new VerticalPanel();

		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel
				.add(new HTML(
						"<br><b>A continuacion los links a los reportes generados:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.add(linksDialogPanel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				addAppButton.setEnabled(true);
				addAppButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				includeApplication();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					includeApplication();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void includeApplication() {
				invokeAsynchronousService();
			}

			private void invokeAsynchronousService() {
				addAppButton.setEnabled(false);
				addAppButton.setFocus(false);

				processDialogBox.center();
				processDialogBox.show();
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		addAppButton.addClickHandler(handler);
	}

	private void resetInterface(final Button sendButton,
			final DialogBox processDialogBox,
			final VerticalPanel applicationsPanel,
			final TextBoxWithPlaceholder repositoryName,
			final TextBoxWithPlaceholder repositoryURL,
			final List<List<TextBoxWithPlaceholder>> applications,
			final Map<String, List<ModuleView>> modules) {
		processDialogBox.hide();

		applications.clear();
		modules.clear();
		applicationsPanel.clear();

		repositoryName.setText(null);
		repositoryURL.setText(null);

		sendButton.setEnabled(true);
		sendButton.setFocus(true);
	}


//	private void invokeAsynchronousApplicationsQuery(final SbeListBox multiBox) {
//
//		reportService.getApplications(
//				new AsyncCallback<List<String>>() {
//					public void onFailure(Throwable caught) {
//						//do nothing
//					}
//
//					public void onSuccess(List<String> result) {
//						for (String app : result) {
//							multiBox.addItem(app, app);
//						}
//						multiBox.setWidth("11em");
//						multiBox.setVisibleItemCount(10);
//					}
//				});
//	}
}
